package com.yc.controller;

import com.entity.Captcha;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vo.Result;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@RestController
public class UserController {
    @Resource
    UserAction userAction;

    @RequestMapping("toregister_user")
    public void toRegister(HttpServletResponse response) throws IOException {
        response.sendRedirect("/user_register.html");
    }
    @RequestMapping("tologin_user")
    public void toLogin(HttpServletResponse response) throws IOException {
        response.sendRedirect("/user_login.html");
    }
    @RequestMapping("user/login")
    public Result login(@RequestParam("phone") String phone, @RequestParam("password") String password){
        return userAction.tologin(phone,password);
    }

    @RequestMapping("tocaptchaCode")
    public @ResponseBody Result toCaptchaCode(HttpSession session) throws IOException {
        Result result=userAction.toCaptchaCode();
        ObjectMapper objectMapper = new ObjectMapper();
        Captcha captcha=objectMapper.convertValue( result.getData(), Captcha.class);
        session.setAttribute("number",captcha.getNumber());
        return result;
    }

    @RequestMapping("user/register")
    public Result toregister(@RequestParam("captchaCode") String captchaCode,@RequestParam("password") String password,@RequestParam("phone") String phone,HttpSession session){
        System.out.println("captchaCode:"+captchaCode+"\tpassword:"+password+"\tphone:"+phone);
        String number=session.getAttribute("number")+"";
        Result result=new Result();
        if(!captchaCode.equalsIgnoreCase(number)){
            result.setCode(0);
            result.setMsg("验证码错误");
            return result;
        }
        return userAction.toregister(password,phone);
    }
}
